package cn.sxt.seata.service.impl;

import cn.sxt.seata.entity.Order;
import cn.sxt.seata.feign.AccountService;
import cn.sxt.seata.feign.StorageService;
import cn.sxt.seata.mapper.OrderMapper;
import cn.sxt.seata.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @description: --
 * @author：Bing
 * @date：2021/4/19 14:36
 * @version：1.0
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private StorageService storageService;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private AccountService accountService;

    @Override
    public int deleteByPrimaryKey(Long id) {
        return orderMapper.deleteByPrimaryKey(id);
    }

    @Override  //任何异常都回滚
    @GlobalTransactional(name = "fsp-create-order",rollbackFor = Exception.class)
    public void insert(Order order) {
        log.info("新建订单");
        orderMapper.insert(order);
        log.info("库存扣减");
        storageService.decrease(order.getProductId(), order.getCount());
        log.info("账户金额减少");
        accountService.decrease(order.getUserId(), order.getMoney());

        log.info("更改订单状态");
        Order newOrder = Order.builder().id(order.getId()).status(1).build();
        orderMapper.updateByPrimaryKeySelective(newOrder);
        log.info("订单创建成功------------------------------------>");
    }

    @Override
    public int insertSelective(Order record) {
        return orderMapper.insertSelective(record);
    }

    @Override
    public Order selectByPrimaryKey(Long id) {
        return orderMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Order record) {
        return orderMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Order record) {
        return orderMapper.updateByPrimaryKey(record);
    }

}
